// 做别名替换，tsc 不会替换路径
require('module-alias/register');
import express from 'express';
import * as bodyParser from 'body-parser';
import {NextFunction, Request, Response} from 'express';
import {baseRoutes} from './route';
import {Route} from '@srcTypes/route';
import process from 'process';
import {lark} from '@/config';

const app = express();
const cors = require('cors');
// 限制请求体大小为20MB
app.use(bodyParser.urlencoded({limit: '100mb', extended: true}));
app.use(bodyParser.json({limit: '100mb'}));

// 错误处理函数
app.use(function (err: Error, req: Request, res: Response, next: NextFunction) {
    return res.sendStatus(500);
});

// 处理跨域问题
app.use(cors());
app.use((req: Request, res: Response, next: NextFunction) => {
    if (req.path !== '/' && !req.path.includes('.')) {
        res.set({
            'Access-Control-Allow-Credentials': true,
            'Access-Control-Allow-Origin': req.headers.origin || '*',
            'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
            'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
            'Content-Type': 'application/json; charset=utf-8',
        });
    }
    // options 快速返回
    req.method === 'OPTIONS' ? res.status(200).end() : next();
});

// 注册所有的路由
baseRoutes.forEach((route: Route) => {
    const {method, path, middleware, handler} = route;
    console.log(method, '-------', path);
    app[method](path, ...middleware, handler);
});

// 进入应用首页
app.get('/', (req: Request, res: Response) => {
    res.sendFile('/Users/admin/Documents/project/feishu-openapi-node/server-node/index.html');
});

// 处理程序异常中断
const handlerInterrupter = (code) => {
    console.log(`退出错误码：${code}`);
    // dbFile.serialize();
};
process.on('SIGINT', handlerInterrupter);
// process.on('exit', handlerInterrupter);
// process.on('SIGKILL', handlerInterrupter);

// 监听端口
app.listen(lark.env.port, lark.env.hostname, () => {
    console.log(`服务运行在 http://${lark.env.hostname}:${lark.env.port} 端口上，访问 /test 将会返回 服务已成功开启`);
});

